package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class EmployeeImplService implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    public void save (Employee employee, Long[] ids) {

        //对密码加密,将用户名当做盐
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
        employee.setPassword(md5Hash.toString());
        //保存到数据库
        employeeMapper.insert(employee);

       /* if (ids != null && ids.length > 0) {
            for (Long rid : ids) {
                employeeMapper.insertRelation(employee.getId(),rid);
            }
        }*/

        //第二种方法用一条sql添加多条数据
        if (ids != null && ids.length > 0) {
            employeeMapper.insertBatchRelation(employee.getId(), ids);
        }

    }

    public void updateById (Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);

        employeeMapper.deleteBatchRelation(employee.getId());

        if (ids != null && ids.length > 0) {
            employeeMapper.insertBatchRelation(employee.getId(), ids);
        }
    }

    public void deleteById (Long id) {
        employeeMapper.deleteByPrimaryKey(id);

        employeeMapper.deleteBatchRelation(id);
    }

    public Employee selectById (Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    public List<Employee> listAll () {
        return employeeMapper.selectAll();
    }

    public PageInfo<Employee> query (QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());

        List<Employee> result = employeeMapper.queryForList(qo);

        return new PageInfo<>(result);
    }

    public Employee login (String username, String password) {
        //查询数据库中是否有能匹配上的数据
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null) { //登录失败
            //通知调用者这里失败了
            throw new RuntimeException("账号和密码不匹配");
        }
        //登录成功,把当前登录成功的对象存入session中,供后期登录校验;
        return employee;
    }


    public void updateNewPassword (Long id, String password) {
        Employee employee = new Employee();
        /*//对密码加密,将用户名当做盐
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(),employee.getName());
        employee.setPassword(md5Hash.toString());*/

        employeeMapper.updateNewPassword(id, password);

    }

    @Override
    public void batchDelete (Long[] ids) {
        employeeMapper.batchDelete(ids);

    }

    @Override
    public Employee selectByName (String name) {
        return employeeMapper.selectByName(name);
    }

    @Override
    public void updateStatus (Long id, boolean status) {
        employeeMapper.updateStatus(id, status);
    }

    @Override
    public Workbook exportXls () {
        //查所有员工
        List<Employee> employees = employeeMapper.selectAll();
        //创建workbook,excel
        Workbook workbook = new HSSFWorkbook();
        //创建一页纸
        Sheet sheet = workbook.createSheet("员工通讯录");

        //创建第一行设置设置为标题行
        Row row = sheet.createRow(0);

        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");

        //遍历每一个员工
        for (int i = 0; i < employees.size(); i++) {
            //获取每一个员工对象
            Employee employee = employees.get(i);
            //从第二行开始
            row = sheet.createRow(i + 1);
            //设置员工的信息参数在每一列中
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());

        }
        return workbook;
    }

    @Override
    public void importXls (MultipartFile file) throws IOException {

        Workbook workbook = new HSSFWorkbook(file.getInputStream());

        //读取第一页纸
        Sheet sheet = workbook.getSheetAt(0);

        int lastRowNum = sheet.getLastRowNum();

        //遍历每一行,从第二行开始
        for (int i = 1; i <= lastRowNum; i++) {
            //创建员工对象
            Employee employee = new Employee();
            //获取每一行
            Row row = sheet.getRow(i);

            String name = row.getCell(0).getStringCellValue();
            //判空
            if (StringUtils.hasLength(name)) {
                employee.setName(name);
            }

            String email = row.getCell(1).getStringCellValue();
            employee.setEmail(email);


            CellType type = row.getCell(2).getCellType();
            if (type.equals(CellType.STRING)){
                //如果是文本类型的单元格
                String age = row.getCell(2).getStringCellValue();
                employee.setAge(Integer.valueOf(age));
            }else {
                //如果是数值类型的单元格
                double value = row.getCell(2).getNumericCellValue();
                employee.setAge((int) value);
            }
            //设置默认密码
            employee.setPassword("1");
            //保存到数据库
            this.save(employee, null);
        }

    }

    @Override
    public List<Employee> selectByRoleSn (String... sns) {
        return employeeMapper.selectByRoleSn(sns);
    }


}